// Decompiled by DJ v3.11.11.95 Copyright 2009 Atanas Neshkov  Date: 22/03/2011 12:25:18 p.m.
// Home Page: http://members.fortunecity.com/neshkov/dj.html  http://www.neshkov.com/dj.html - Check often for new version!
// Decompiler options: packimports(3) 
// Source File Name:   PedidoForm.java

package com.luxsoft.sw3.impap.ui.form;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.swing.EventSelectionModel;
import ca.odell.glazedlists.swing.EventTableModel;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.adapter.Bindings;
import com.jgoodies.binding.list.SelectionInList;
import com.jgoodies.binding.value.ConverterFactory;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.*;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.uifextras.util.ActionLabel;
import com.jgoodies.uifextras.util.UIFactory;
import com.jgoodies.validation.view.ValidationResultViewFactory;
import com.luxsoft.siipap.swing.actions.DispatchingAction;
import com.luxsoft.siipap.swing.binding.Binder;
import com.luxsoft.siipap.swing.controls.UpperCaseField;
import com.luxsoft.siipap.swing.form2.AbstractForm;
import com.luxsoft.siipap.swing.form2.IFormModel;
import com.luxsoft.siipap.swing.utils.*;
import com.luxsoft.siipap.util.DBUtils;
import com.luxsoft.sw3.ventas.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.VerticalLayout;
import org.jdesktop.swingx.table.TableColumnExt;

// Referenced classes of package com.luxsoft.sw3.impap.ui.form:
//            PedidoController, PedidoHeader, UIUtils

public class PedidoForm extends AbstractForm
    implements ActionListener, ListSelectionListener
{
    private class BeanHandler        implements PropertyChangeListener    {

        public void propertyChange(PropertyChangeEvent evt)
        {
            header.updateHeader();
            if(evt.getPropertyName().equals("tipo"))
                if(com.luxsoft.sw3.ventas.Pedido.Tipo.CREDITO.equals(evt.getNewValue()))
                    getControl("formaDePago").setEnabled(false);
                else
                    getControl("formaDePago").setEnabled(true);
        }        
    }

    private class KeyHandler
        implements KeyEventPostProcessor
    {

        public boolean postProcessKeyEvent(KeyEvent e)
        {
            if(401 == e.getID())
                if(KeyStroke.getKeyStroke("F12").getKeyCode() == e.getKeyCode())
                {
                    if(getController().getPedido().getId() == null && isFocused())
                    {
                        e.consume();
                        seleccionarCliente();
                        return true;
                    }
                } else
                if(KeyStroke.getKeyStroke("F7").getKeyCode() == e.getKeyCode())
                {
                    if(getController().getPedido().getId() == null && isFocused())
                    {
                        e.consume();
                        return true;
                    }
                } else
                if(KeyStroke.getKeyStroke("INSERT").getKeyCode() == e.getKeyCode())
                {
                    if(isFocused())
                    {
                        e.consume();
                        insertarEntrada();
                        return true;
                    }
                } else
                if(KeyStroke.getKeyStroke("DELETE").getKeyCode() == e.getKeyCode())
                {
                    if(isFocused())
                    {
                        e.consume();
                        deletePartida();
                        return true;
                    }
                } else
                if(KeyStroke.getKeyStroke("F11").getKeyCode() == e.getKeyCode())
                {
                    if(isFocused())
                    {
                        e.consume();
                        edit();
                        return true;
                    }
                } else
                if(KeyStroke.getKeyStroke("F3").getKeyCode() == e.getKeyCode() && isFocused())
                {
                    e.consume();
                    claveField.requestFocusInWindow();
                    return true;
                }
            return false;
        }

       

        private KeyHandler()
        {           
            super();
        }

        
    }


    public PedidoForm(PedidoController controller)
    {
        super(controller);
        setTitle((new StringBuilder("Pedido    [")).append(model.getValue("sucursal")).append("]").toString());
        model.addBeanPropertyChangeListener(beanHandler);
    }

    public PedidoController getController()
    {
        return (PedidoController)getModel();
    }

    protected JComponent buildHeader()
    {
        header = new PedidoHeader();
        header.setPedido(getController().getPedido());
        if(model.getValue("id") != null)
            header.updateHeader();
        return header;
    }

    protected JComponent buildContent()
    {
        JPanel panel = new JPanel(new VerticalLayout(8));
        panel.add(buildFormPanel());
        panel.add(buildGridPanel());
        panel.add(buildToolbarPanel());
        panel.add(buildSouthPanel());
        if(model.isReadOnly())
            panel.add(buildButtonBarWithClose(), "South");
        else
            panel.add(buildButtonBarWithOKCancel(), "South");
        afterMainPanelBuild(panel);
        return panel;
    }

    protected JComponent buildButtonBarWithOKCancel()
    {
        JPanel bar = ButtonBarFactory.buildRightAlignedBar(new JButton[] {
            createOKButton(false), createCancelButton()
        });
        bar.setBorder(Borders.BUTTON_BAR_GAP_BORDER);
        return bar;
    }

    protected JComponent buildFormPanel()
    {
        FormLayout layout = new FormLayout("p,2dlu,150dlu, 2dlu,max(p;50dlu),2dlu,max(p;90dlu), 2dlu,max(p;50dlu),2dlu,max(p;90dlu), 2dlu,max(p;50dlu),2dlu,max(p;90dlu)", "");
        DefaultFormBuilder builder = new DefaultFormBuilder(layout);
        if(getController().getPedido().getId() == null)
            builder.append(getTitleLabel("&Clave"), buildClienteControl());
        builder.append(getTitleLabel("Fecha"), addReadOnly("fecha"));
        builder.append(getTitleLabel("Estado"), addReadOnly("estado"));
        builder.nextLine();
        builder.append("Tipo", getControl("tipo"));
        builder.append(getTitleLabel("Pago"), addReadOnly("formaDePago"));
        builder.append("Facturista", getControl("facturista"));
        builder.append("", addReadOnly("operador"));
        builder.nextLine();
        builder.append("Pedimento", getControl("pedimento"));
        builder.append("Fecha", getControl("pedimentoFecha"));
        builder.append("Aduana", getControl("aduana"));
        builder.nextLine();
        builder.append("Comentario", getControl("comentario"), 9);
        ActionLabel entregaLabel = new ActionLabel("Direcci\363n");
        entregaLabel.setFont(TITLE_LABEL_FONT);
        entregaLabel.addActionListener((ActionListener)EventHandler.create(ActionListener.class, getController(), "definirFormaDeEntrega"));
        builder.nextLine();
        ComponentUtils.decorateSpecialFocusTraversal(builder.getPanel());
        if(getController().getPedido().getId() == null)
            ComponentUtils.decorateTabFocusTraversal(claveField);
        return builder.getPanel();
    }

    private JComponent buildSouthPanel()
    {
        FormLayout layout = new FormLayout("p:g,3dlu,l:p,3dlu,r:p,3dlu,r:p", "t:p,3dlu");
        PanelBuilder builder = new PanelBuilder(layout);
        CellConstraints cc = new CellConstraints();
        builder.add(buildValidationPanel(), cc.xy(1, 1));
        builder.add(buildTotalesPane_1(), cc.xy(3, 1));
        builder.add(buildTotalesPane_2(), cc.xy(5, 1));
        builder.add(buildTotalesPane_3(), cc.xy(7, 1));
        return builder.getPanel();
    }

    private JComponent buildTotalesPane_1()
    {
        FormLayout layout = new FormLayout("p,2dlu,80dlu", "");
        DefaultFormBuilder builder = new DefaultFormBuilder(layout);
        builder.appendSeparator("Importes ");
        builder.append("Bruto ", addReadOnly("importeBruto"), true);
        builder.append("Descuento", addReadOnly("importeDescuento"));
        builder.append("Cortes ", addReadOnly("importeCorte"), true);
        builder.append("Sub Total 1 ", addReadOnly("subTotal1"), true);
        return builder.getPanel();
    }

    private JComponent buildTotalesPane_2()
    {
        FormLayout layout = new FormLayout("p,2dlu,80dlu", "");
        DefaultFormBuilder builder = new DefaultFormBuilder(layout);
        builder.appendSeparator("Cargos");
        builder.append("Maniobra T ", addReadOnly("comisionTarjetaImporte"));
        builder.append("Maniobra F", getControl("flete"), true);
        return builder.getPanel();
    }

    private JComponent buildTotalesPane_3()
    {
        FormLayout layout = new FormLayout("p,2dlu,80dlu", "");
        DefaultFormBuilder builder = new DefaultFormBuilder(layout);
        builder.appendSeparator("Total");
        builder.append("Sub Total 2 ", addReadOnly("subTotal"));
        builder.append("Impuesto ", addReadOnly("impuesto"));
        builder.append("A Pagar  ", addReadOnly("total"));
        return builder.getPanel();
    }

    protected JComponent buildValidationPanel()
    {
        java.awt.Color color = UIManager.getColor("Label.background");
        JComponent c = ValidationResultViewFactory.createReportList(model.getValidationModel(), color);
        c.setBorder(null);
        JScrollPane sp = (JScrollPane)c;
        sp.setBorder(BorderFactory.createTitledBorder(Borders.EMPTY_BORDER, "Validaci\363n"));
        JList list = (JList)sp.getViewport().getView();
        list.setFont(new Font("SansSerif", 1, 13));
        return c;
    }

    private JLabel getTitleLabel(String text)
    {
        JLabel label = DefaultComponentFactory.getInstance().createTitle(text);
        label.setFont(label.getFont().deriveFont(1, 13F));
        return label;
    }

    protected JComponent createCustomComponent(String property)
    {
        if("clave".equals(property))
        {
            claveField = new UpperCaseField();
            claveField.addActionListener(this);
            claveField.getActionMap().put("insert", getInsertAction());
            claveField.getInputMap().put(KeyStroke.getKeyStroke("INSERT"), "insert");
            return claveField;
        }
        if("tipo".equals(property))
        {
            SelectionInList sl = new SelectionInList(com.luxsoft.sw3.ventas.Pedido.Tipo.values(), model.getModel(property));
            JComboBox box = BasicComponentFactory.createComboBox(sl);
            box.setPrototypeDisplayValue("M O S T R A D O R");
            return box;
        }
        if("formaDePago".equals(property))
        {
            SelectionInList sl = new SelectionInList(getController().getFormasDePago(), model.getModel(property));
            JComboBox box = BasicComponentFactory.createComboBox(sl);
            box.setPrototypeDisplayValue("TARJETA DE CREDITO");
            return box;
        }
        if("entrega".equals(property))
        {
            SelectionInList sl = new SelectionInList(com.luxsoft.sw3.ventas.Pedido.FormaDeEntrega.values(), model.getModel(property));
            JComboBox box = BasicComponentFactory.createComboBox(sl);
            return box;
        }
        if(property.startsWith("importe"))
        {
            JComponent c = Binder.createBigDecimalForMonyBinding(model.getModel(property));
            return c;
        }
        if(property.startsWith("impu") || property.startsWith("total") || property.startsWith("flete") || property.equals("comisionTarjetaImporte") || property.startsWith("sub"))
        {
            JComponent c = Binder.createBigDecimalForMonyBinding(model.getModel(property), true);
            return c;
        }
        if("fecha".equals(property))
        {
            JFormattedTextField tf = BasicComponentFactory.createFormattedTextField(model.getModel(property), new SimpleDateFormat("dd/MM/yyyy"));
            tf.setEditable(false);
            return tf;
        }
        if("instruccionDeEntrega".equals(property))
        {
            JTextArea ta = UIFactory.createMultilineLabel("<h3>Direcci\363n</h3>");
            ta.setBorder(BorderFactory.createEtchedBorder());
            com.jgoodies.binding.value.ValueModel vm = ConverterFactory.createStringConverter(model.getModel(property), new com.luxsoft.sw3.ventas.InstruccionDeEntrega.StringFormat());
            Bindings.bind(ta, vm);
            return UIFactory.createStrippedScrollPane(ta);
        }
        if("mismaDireccion".equals(property))
        {
            JComponent c = BasicComponentFactory.createCheckBox(model.getModel(property), "Misma");
            c.setEnabled(!model.isReadOnly());
            return c;
        }
        if("comprador".equals(property))
        {
            JComponent c = Binder.createMayusculasTextField(model.getModel(property));
            c.setEnabled(!model.isReadOnly());
            return c;
        }
        if("mismoComprador".equals(property))
        {
            JComponent c = BasicComponentFactory.createCheckBox(model.getModel(property), "Mismo");
            c.setEnabled(!model.isReadOnly());
            return c;
        }
        if("facturista".equals(property))
        {
            JComponent c = BasicComponentFactory.createPasswordField(getController().getPasswordHolder(), true);
            c.setEnabled(!model.isReadOnly());
            return c;
        }
        if("operador".equals(property))
            return BasicComponentFactory.createLabel(getController().getFacturistaHolder());
        if("aduana".equals(property))
        {
            JComponent c = Binder.createMayusculasTextField(model.getModel(property));
            c.setEnabled(!model.isReadOnly());
            return c;
        } else
        {
            return super.createCustomComponent(property);
        }
    }

    private JComponent buildClienteControl()
    {
        FormLayout layout = new FormLayout("70dlu:g,2dlu,p,2dlu,p", "");
        DefaultFormBuilder builder = new DefaultFormBuilder(layout);
        JButton bt1 = new JButton(getLookupAction());
        bt1.setFocusable(false);
        JButton bt2 = new JButton(getInsertCliente());
        bt2.setFocusable(false);
        builder.append(getControl("clave"), bt1, bt2);
        return builder.getPanel();
    }

    protected void afterMainPanelBuild(JPanel panel)
    {
        model.validate();
        ajustarActions(panel);
        ajustarFont(panel);
    }

    private void ajustarFont(Container panel)
    {
        UIUtils.increaseFontSize(panel, 1.0F);
    }

    protected JPanel buildToolbarPanel()
    {
        getInsertAction().putValue("Name", "Agregar [INS]");
        getInsertAction().putValue("SmallIcon", ResourcesUtils.getIconFromResource("images2/cart_add.png"));
        getDeleteAction().putValue("Name", "Eliminar [SUP]");
        getEditAction().putValue("Name", "Editar [F11]");
        getViewAction().putValue("Name", "Consultar");
        getInsertarEntradaAction().putValue("AcceleratorKey", KeyStroke.getKeyStroke("INSERT"));
        JButton insertarEntradaButton = new JButton(getInsertarEntradaAction());
        setDefaultButton(insertarEntradaButton);
        JButton insertButton = new JButton(getInsertAction());
        JButton buttons[] = {
            insertarEntradaButton, insertButton, new JButton(getDeleteAction()), new JButton(getEditAction())
        };
        return ButtonBarFactory.buildLeftAlignedBar(buttons, true);
    }

    public Action getInsertarEntradaAction()
    {
        if(insertarEntradaAction == null)
        {
            insertarEntradaAction = new DispatchingAction(this, "insertarEntrada");
            insertarEntradaAction.putValue("Name", "Embarque");
        }
        return insertarEntradaAction;
    }

    public Action getLookupAction()
    {
        if(lookupAction == null)
        {
            lookupAction = new DispatchingAction(this, "seleccionarCliente");
            lookupAction.putValue("SmallIcon", ResourcesUtils.getIconFromResource("images/misc2/page_find.png"));
            lookupAction.putValue("Name", "F2");
        }
        return lookupAction;
    }

    public Action getInsertCliente()
    {
        if(insertCliente == null)
        {
            insertCliente = new DispatchingAction(getController(), "insertarClienteNuevo");
            insertCliente.putValue("SmallIcon", ResourcesUtils.getIconFromResource("images2/user_add.png"));
            insertCliente.putValue("Name", "F7");
        }
        return insertCliente;
    }

    public Action getImprimirAction()
    {
        if(imprimirAction == null)
        {
            imprimirAction = CommandUtils.createPrintAction(this, "imprimir");
            imprimirAction.putValue("Name", "Imprimir [F12]");
        }
        return imprimirAction;
    }

    public Action getDescuentoEspecialAction()
    {
        if(descuentoEspecialAction == null)
        {
            descuentoEspecialAction = new DispatchingAction(this, "solicitarDescuentoEspecial");
            descuentoEspecialAction.putValue("Name", "Descto Especial");
            descuentoEspecialAction.putValue("SmallIcon", ResourcesUtils.getIconFromResource("images2/money_delete.png"));
        }
        return descuentoEspecialAction;
    }

    public Action getFacturarAction()
    {
        if(facturarAction == null)
        {
            facturarAction = new DispatchingAction(this, "facturar");
            facturarAction.putValue("Name", "Facturar");
            facturarAction.putValue("SmallIcon", ResourcesUtils.getIconFromResource("images2/money_dollar.png"));
        }
        return facturarAction;
    }

    protected void ajustarActions(JPanel panel)
    {
        getOKAction().putValue("Name", "Salvar [F10]");
        getOKAction().putValue("SmallIcon", ResourcesUtils.getIconFromResource("images/edit/save_edit.gif"));
        getCancelAction().putValue("Name", "Cancelar");
        ComponentUtils.addAction(panel, new AbstractAction() {

            public void actionPerformed(ActionEvent e)
            {
                if(getOKAction().isEnabled())
                    getOKAction().actionPerformed(null);
            }

            
        }
, KeyStroke.getKeyStroke("F10"), 2);
        ComponentUtils.addInsertAction(panel, getInsertAction());
    }

    protected JComponent buildGridPanel()
    {
        String propertyNames[] = {
            "clave", "descripcion", "producto.gramos", "producto.calibre", "cantidad", "descripcionCorte", "precio", "importeBruto", "descuento", "importeDescuento", 
            "cortes", "importeCorte", "subTotal"
        };
        String columnLabels[] = {
            "Clave", "Producto", "(g)", "cal", "Cant", "Corte", "Precio", "Imp Bruto", "Des (%)", "Des ($)", 
            "Cortes (#)", "Cortes ($)", "Sub Total"
        };
        boolean edits[] = {
            false, false, false, false, false, false, true, false, false, false, 
            false, false, false
        };
        ca.odell.glazedlists.gui.TableFormat tf = GlazedLists.tableFormat(PedidoDet.class, propertyNames, columnLabels, edits);
        EventTableModel tm = new EventTableModel(getController().getPartidasSource(), tf);
        grid = ComponentUtils.getStandardTable();
        grid.setModel(tm);
        selectionModel = new EventSelectionModel(getController().getPartidasSource());
        selectionModel.addListSelectionListener(this);
        grid.setSelectionModel(selectionModel);
        ComponentUtils.decorateActions(grid);
        ComponentUtils.addInsertAction(grid, getInsertAction());
        ComponentUtils.addDeleteAction(grid, getDeleteAction());
        grid.setEnabled(!model.isReadOnly());
        JComponent gridComponent = ComponentUtils.createTablePanel(grid);
        gridComponent.setPreferredSize(new Dimension(850, 300));
        Font font = grid.getFont().deriveFont(grid.getFont().getSize2D() + 2.0F);
        grid.setFont(font);
        grid.setColumnControlVisible(false);
        grid.getColumnExt("Des (%)").setCellRenderer(Renderers.getPorcentageRenderer());
        return gridComponent;
    }

    public void insertPartida()
    {
        getController().insertarPartida();
        grid.packAll();
        grid.requestFocusInWindow();
    }

    public void insertarEntrada()
    {
        getController().insertarPorEntrada();
        grid.packAll();
        grid.requestFocusInWindow();
    }

    public void edit()
    {
        if(!selectionModel.isSelectionEmpty())
        {
            PedidoDet selected = (PedidoDet)selectionModel.getSelected().get(0);
            getController().editar(selected);
        }
    }

    public void deletePartida()
    {
        if(!selectionModel.isSelectionEmpty())
        {
            for(int index = selectionModel.getMinSelectionIndex(); index <= selectionModel.getMaxSelectionIndex(); index++)
                getController().eliminarPartida(index);

        }
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == claveField)
        {
            String clave = claveField.getText();
            claveField.transferFocus();
            getController().asignarCliente(clave);
        }
    }

    public void valueChanged(ListSelectionEvent e)
    {
        boolean val = !selectionModel.isSelectionEmpty();
        if(model.isReadOnly())
            val = false;
        getController().actualizarImportes();
        getEditAction().setEnabled(val);
        getDeleteAction().setEnabled(val);
        getViewAction().setEnabled(!selectionModel.isSelectionEmpty());
    }

    protected void onWindowOpened()
    {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(keyHandler);
        if(claveField != null)
            claveField.requestFocusInWindow();
    }

    public void close()
    {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(keyHandler);
        model.removeBeanPropertyChangeListener(beanHandler);
        super.close();
    }

    public void seleccionarCliente()
    {
        getController().seleccionarCliente(this);
    }

    public void consolidarCortes()
    {
        JOptionPane.showMessageDialog(getContentPane(), "EN DESARROLLO");
    }

    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable() {

            public void run()
            {
                DBUtils.whereWeAre();
                SWExtUIManager.setup();
                PedidoController model = new PedidoController();
                PedidoForm form = new PedidoForm(model);
                form.open();
                if(!form.hasBeenCanceled())
                {
                    PedidoForm.showObject(model.getBaseBean());
                    model.persist();
                }
                System.exit(0);
            }

        }
);
    }

    private final Font TITLE_LABEL_FONT = new Font("SansSerif", 1, 13);
    PedidoHeader header;
    final BeanHandler beanHandler = new BeanHandler();
    private final KeyEventPostProcessor keyHandler = new KeyHandler();
    private JTextField claveField;
    private Action lookupAction;
    private Action insertCliente;
    private Action imprimirAction;
    private Action descuentoEspecialAction;
    private Action facturarAction;
    private Action insertarEntradaAction;
    private JXTable grid;
    private EventSelectionModel selectionModel;


}
